package com.example.service;

import com.example.entity.Order;
import com.example.repository.OrderRepository;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * datetime : 2020/10/7 8:06
 * author : shenxiang
 */
@Service
public class OrderService {

    @Autowired
    private OrderRepository orderRepository;

    public Order getOneById(Long id){
        Optional<Order> repositoryById = orderRepository.findById(id);
        return repositoryById.orElse(null);
    }

    public Order save(Order order){
        return orderRepository.save(order);
    }

    public void deleteById(Long id){
        orderRepository.deleteById(id);
    }

    public List<Order> getAll(){
        return orderRepository.findAll();
    }

    /**
     * 根据订单号查询该订单的行记录
     * @param orderNo
     * @return
     */
    public Order getOneByOrderNo(String orderNo){
        Order param = new Order();
        param.setOrderNo(orderNo);
        Example<Order> example = Example.of(param);
        Optional<Order> repositoryOne = orderRepository.findOne(example);
        return repositoryOne.orElse(null);
    }

    /**
     * 根据订单号将订单状态设置为已取消
     * @param orderNo
     * @return
     */
    public boolean setCancelByOrderNo(String orderNo){
        return orderRepository.updateStatusByOrderNo(orderNo, 2, new Date()) > 0;
    }

    /**
     * 根据订单号将订单状态设置为支付成功
     * @param orderNo
     * @return
     */
    public boolean setPayedByOrderNo(String orderNo){
        return orderRepository.updateStatusByOrderNo(orderNo, 1, new Date()) > 0;
    }
}
